/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package CONTROLLERS;

import BEANS.ComboItem;
import BEANS.Product;
import UTIL.TableManager;
import UTIL.DatabaseConnector;
import UTIL.InputValidator;
import VIEW.ProductsUI;
import datechooser.beans.DateChooserCombo;
import java.awt.Color;
import java.awt.Point;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collections;
import java.util.Date;
import javax.swing.JComboBox;
import javax.swing.JDialog;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JRadioButton;
import javax.swing.JTable;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.table.DefaultTableModel;
/**
 *
 * @author Belthazod
 */
public class CartController{
    private JTextField receiptno;
    private TableManager cartTableManager;
    private TableManager inventoryTableManager;
    private TableManager salesHistoryTableManager;
    private JDialog salesTypeDialog;
    private JDialog inputQuantityDialog;
    private JDialog inputSerialDialog;
    private JDialog editQuantityDialog;
    private JDialog editSerialDialog;
    private JTable cartTable;
    private static JLabel receiptInfoLabel1;
    private static JLabel receiptInfoLabel2;
    private static JTextField receiptNumberInput;
    private JTextField inventorySearchInput;
    private JTextField inputQuantity;
    private JTextField inputSerial;
    private JTextArea remarksInput;
    private ProductController productController;
    private JLabel clearMark;
    private DateChooserCombo salesDate;
    private DateChooserCombo dateTo;
    private DateChooserCombo dateFrom;
    private JTextField receiptNumber;
    private JComboBox<ComboItem> productFilterCategoryComboBox;
    private JComboBox<ComboItem> sortByComboBox;
    private static ArrayList<Product> productList;
    private JComboBox<ComboItem> productFilterSupplierComboBox;
    private JTextField editQuantity;
    private JTextField editSerial;
    private DatabaseConnector dbConnector = DatabaseConnector.getInstance();
    private static String activeOrder = "4";
    private JTextField inputLength;
    private JDialog input;
    private JDialog addWire;
    private JRadioButton whole;
    private JRadioButton partial;
    
    public CartController(JComboBox<ComboItem> productFilterCategoryComboBox, 
            JTable cartTable, JTable inventoryTable, 
            JTextField inventoryTableSearchInput, 
            JLabel clearMark, JDialog salesTypeDialog, 
            DateChooserCombo salesDate, JTextField receiptNumber, 
            JComboBox<ComboItem> productFilterSupplierComboBox, JDialog inputQuantityDialog, 
            JDialog inputSerialDialog, JTextField inputQuantity, 
            JTextField inputSerial, JTextField editQuantity, JTextField editSerial,
            JDialog editQuantityDialog, JDialog editSerialDialog, JTextField receiptno,
            JTextArea remarksInput, JTable salesHistory, DateChooserCombo dateTo, 
            DateChooserCombo dateFrom, JDialog input, JTextField inputLength,
            JDialog addWire, JRadioButton whole, JRadioButton partial){
        
        this.addWire = addWire;
        this.whole = whole;
        this.partial = partial;
        this.input = input;
        this.inputLength = inputLength;
        this.cartTableManager = new TableManager(cartTable);
        this.salesHistoryTableManager = new TableManager(salesHistory);
        cartTableManager.setAutoClear(true);
        this.cartTable = cartTable;
        this.editSerial = editSerial;
        this.receiptno = receiptno;
        inventoryTableManager = new TableManager(inventoryTable);
        inventorySearchInput = inventoryTableSearchInput;
        this.inputQuantity = inputQuantity;
        this.inputSerial = inputSerial;
        this.editQuantity = editQuantity;
        productController = new ProductController();
        inventoryTableManager.alignCellRight(4);
        this.productFilterCategoryComboBox = productFilterCategoryComboBox;
        this.clearMark = clearMark;
        this.inputQuantityDialog = inputQuantityDialog;
        this.inputSerialDialog = inputSerialDialog;
        this.salesTypeDialog = salesTypeDialog;
        this.editQuantityDialog = editQuantityDialog;
        this.editSerialDialog = editSerialDialog;
        this.salesDate = salesDate;
        this.receiptNumber = receiptNumber;       
        productList = ProductController.getProductList();
        this.productFilterSupplierComboBox = productFilterSupplierComboBox;
        this.remarksInput = remarksInput;
        this.dateTo = dateTo;
        this.dateFrom = dateFrom;
        inventoryTableManager.hideColumn(6);
        cartTableManager.hideColumn(8);
        
//        Calendar day = Calendar.getInstance();
//        day.set(day.get(Calendar.YEAR), day.get(Calendar.MONTH), day.get(Calendar.DATE));
//        day.add(Calendar.MONTH, -1);
//        dateFrom.setSelectedDate(day);
        
    }
    
    public boolean exceed(){
     ArrayList<String> numdata = new ArrayList<String>();
     int currentQuantity = Integer.parseInt(inventoryTableManager.getValueAt(inventoryTableManager.getSelectedRow(), 4));
     String current = inventoryTableManager.getValueAt(inventoryTableManager.getSelectedRow(), 2);
            for (int count = 0; count < cartTableManager.getRowCount(); count++){
            numdata.add(cartTableManager.getValueAt(count, 2).toString());
            }
            int occurrences = Collections.frequency(numdata, current);
            if(currentQuantity <= occurrences){
                return false;
            }else{
                return true;
            }
        }   
    public void addToCart(){
        try{           
            int currentQuantity = Integer.parseInt(inventoryTableManager.getValueAt(inventoryTableManager.getSelectedRow(), 4));
            String productName = inventoryTableManager.getValueAt(inventoryTableManager.getSelectedRow(), 2);
            String warranty = (String) inventoryTableManager.getValueAt(inventoryTableManager.getSelectedRow(), 1);
            if(currentQuantity != 0){
                
                boolean itemExists = false;
                String productID = inventoryTableManager.getIDFromTable(inventoryTableManager.getSelectedRow());
                String existingProductName = "";
                String unit = inventoryTableManager.getValueAt(inventoryTableManager.getSelectedRow(), 6);
                for(int row = 0; row < cartTableManager.getRowCount() && Integer.parseInt(inventoryTableManager.getValueAt(inventoryTableManager.getSelectedRow(), 1)) == 0; row++){

                    String truckProductID = cartTableManager.getIDFromTable(row);
                    
                   
                    if(productID.equals(truckProductID)){
                        itemExists = true;
                        existingProductName = inventoryTableManager.getValueAt(inventoryTableManager.getSelectedRow(), 2);
                        break;
                    }
                    
                }
                if(unit.equals("roll")){
                     addWire.setVisible(true);
                 }else if(itemExists){

                JOptionPane.showMessageDialog(null,
                    existingProductName + " is already in the list.",
                    "Error",
                    JOptionPane.ERROR_MESSAGE);
                }else{
                if(exceed()){
                 if(Integer.parseInt(warranty)>0){
                    inputSerialDialog.setVisible(true);
                 }else{
                    inputQuantityDialog.setVisible(true);
                 }
                }else{
                    JOptionPane.showMessageDialog(null, "Insufficient stock for " + productName + ". Cannot add to cart.", "Insufficient Stock", JOptionPane.ERROR_MESSAGE);
                }
                }
            }else{
                JOptionPane.showMessageDialog(null, "There is no available stock for " + productName + ". Cannot add to list.", "No Stock", JOptionPane.ERROR_MESSAGE);
            }
        }catch(NullPointerException | IndexOutOfBoundsException npe){
            //JOptionPane.showMessageDialog(null, "Please select an item from the table to mark as bought.", "Product Selection Error", JOptionPane.ERROR_MESSAGE);
        }catch(Exception e){
            e.printStackTrace();
        }
    }
    
    public void addRoll(){
        if(whole.isSelected()){
            addWire.dispose();
            inputQuantityDialog.setVisible(true);            
        }else if(partial.isSelected()){
            addWire.dispose();
            input.setVisible(true);
        }
    }
    
    public void addRollToCart(){
        try{
        String length = inputLength.getText();
        int valid = Integer.parseInt(length);
        String value = length + "m";
        String productID = inventoryTableManager.getIDFromTable(inventoryTableManager.getSelectedRow());
         String name = (String) inventoryTableManager.getValueAt(inventoryTableManager.getSelectedRow(), 2);
         String supplier = (String) inventoryTableManager.getValueAt(inventoryTableManager.getSelectedRow(), 3);
         String quantity = (String)  inventoryTableManager.getValueAt(inventoryTableManager.getSelectedRow(), 4);
         String warranty = (String) inventoryTableManager.getValueAt(inventoryTableManager.getSelectedRow(), 1);
         String[] values = {productID, warranty, name, supplier, quantity, "Purchase", "", value};
         cartTableManager.addRowContent(values );
         inputLength.setText("");
         input.dispose();
        }catch(NumberFormatException npe){
            JOptionPane.showMessageDialog(null, "Please enter a valid value.", "Invalid Input", JOptionPane.ERROR_MESSAGE);
        }
    }
   
    public void uneditable(JTable table){
        String cell = (String) cartTableManager.getValueAt(cartTableManager.getSelectedRow(), 1);
        int row = cartTableManager.getSelectedRow();
        DefaultTableModel tableModel = new DefaultTableModel() {
        //String c = "";
        @Override
        public boolean isCellEditable(int rowIndex, int columnIndex) {
            if(cell!=""){
        return (rowIndex == row && columnIndex == 1); 
        
            }else{
        return !( rowIndex == row && columnIndex == 1 );
            }
        }
        };
        table.setModel(tableModel);
    }
  
    public void clearCart(){
        
        cartTableManager.clearTableContents();
    }
    
    public void markItemsAsSold(){
        
        boolean dateIsEmpty = false;
        boolean orIsEmpty = false;
        try{
            String salesDateInput = salesDate.getText().split(",")[1].substring(1).concat(","+salesDate.getText().split(",")[2]);

            DateFormat dffrom = new SimpleDateFormat("MMMMM d, yyyy");

            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            if(InputValidator.checkInput(receiptno.getText(), "Please enter a receipt number before checking out.")){
                Date date = dffrom.parse(salesDateInput);
                String dateOfSale = sdf.format(date);
                String receiptNumberInput = receiptno.getText();
                boolean fieldsAreComplete = true;

                //validation for all of the items
                for(int i = 0; i< cartTableManager.getRowCount(); i++){
                    String productID = cartTableManager.getValueAt(i, 0);
                    String productName = cartTableManager.getValueAt(i, 2);
                    String quantity = cartTableManager.getValueAt(i, 7);
                    String serialNumber = cartTableManager.getValueAt(i,6);
                    String warranty = cartTableManager.getValueAt(i, 1);
                    int physicalCount = Integer.parseInt(cartTableManager.getValueAt(i,4));
                    if(Integer.parseInt(warranty) > 0 && serialNumber.trim().equals("")){
                        fieldsAreComplete = false;
                        JOptionPane.showMessageDialog(null, "Please enter the serial number of " + productName, "Empty Serial Number", JOptionPane.ERROR_MESSAGE);
                    }else if(Integer.parseInt(warranty) == 0 && quantity.trim().equals("") ){
                        fieldsAreComplete = false;
                        JOptionPane.showMessageDialog(null, "Please input the quantity of " + productName, "Empty Quantity", JOptionPane.ERROR_MESSAGE);
                    }
//                    if(Integer.parseInt(warranty) == 0 && Integer.parseInt(quantity.trim()) > physicalCount ){
//                        fieldsAreComplete = false;
//                        JOptionPane.showMessageDialog(null, "The set quantity sold for <span style='color:blue'>" + productName + "</span> exceeds the count in stock.", "Quantity exceeded", JOptionPane.ERROR_MESSAGE);
//                    }
//                    if(Integer.parseInt(warranty) == 0 && Integer.parseInt(quantity.trim()) <=0  ){
//                        fieldsAreComplete = false;
//                        JOptionPane.showMessageDialog(null, "The set quantity sold for " + productName + " is invalid.", "Invalid Quantity", JOptionPane.ERROR_MESSAGE);
//                    }
                    ResultSet r = dbConnector.query("SELECT * from returns JOIN warranty using(product_id) JOIN sales_details USING(product_id) WHere product_id = ? AND (warranty.old_serial_number = ? OR warranty.new_serial_number = ? OR sales_details.serial_number = ?)", new String[]{productID, serialNumber, serialNumber, serialNumber} );
                    if(r.next()){
                        fieldsAreComplete = false;
                        JOptionPane.showMessageDialog(null, "The serial number "+ serialNumber +" you have entered for product " + productName + " is already existing. Please double check and try again.", "Serial number already exists", JOptionPane.ERROR_MESSAGE);
                    }

                }
                //if all validation passes
                if(fieldsAreComplete){
                    int result = JOptionPane.showConfirmDialog(null, "Confirm Purchase?", "Confirm Purchase", JOptionPane.YES_NO_OPTION);
                    if(result == 0){
                        dbConnector.insert("INSERT INTO sales(sales_date, receipt_number, remarks) VALUES(?, ?, ?)", new String[]{dateOfSale, receiptNumberInput, remarksInput.getText()});

                        ResultSet rs = dbConnector.query("SELECT sales_id FROM sales ORDER BY 1 DESC");

                        rs.next();

                        for(int i = 0; i< cartTableManager.getRowCount(); i++){
                            try{
                            String productID = cartTableManager.getIDFromTable(i);
                            String quantity = cartTableManager.getValueAt(i, 7);
                            int qty = Integer.parseInt(quantity);
                            String serialNumber = cartTableManager.getValueAt(i,6);
                            String warranty = cartTableManager.getValueAt(i, 1);
                            String purchaseType = cartTableManager.getValueAt(i, 5);

                            if(Integer.parseInt(warranty) > 0 && !serialNumber.equals("")){
                                dbConnector.insert("INSERT INTO sales_details(sales_id, product_id, serial_number, warranty_duration, sales_type) VALUES(?,?,?,?,?)", new String[]{rs.getString(1), productID, serialNumber, warranty, purchaseType});
                                dbConnector.update("UPDATE product SET physical_count = physical_count - 1 WHERE product_id = ?", new String[]{productID});
                            }else if(!quantity.trim().equals("")){
                                dbConnector.insert("INSERT INTO sales_details(sales_id, product_id, quantity_sold, warranty_duration, sales_type) VALUES(?,?,?,?,?)", new String[]{rs.getString(1), productID, quantity, warranty, purchaseType});
                                dbConnector.update("UPDATE product SET physical_count = physical_count - ? WHERE product_id = ?", new String[]{quantity, productID});
                            }
                            }catch(NumberFormatException e){
                                String productID = cartTableManager.getIDFromTable(i);
                                String quantity = "0";
                                String serialNumber = cartTableManager.getValueAt(i,6);
                                String warranty = cartTableManager.getValueAt(i, 1);
                                String purchaseType = cartTableManager.getValueAt(i, 5);

                            if(Integer.parseInt(warranty) > 0 && !serialNumber.equals("")){
                                dbConnector.insert("INSERT INTO sales_details(sales_id, product_id, serial_number, warranty_duration, sales_type) VALUES(?,?,?,?,?)", new String[]{rs.getString(1), productID, serialNumber, warranty, purchaseType});
                                dbConnector.update("UPDATE product SET physical_count = physical_count - 1 WHERE product_id = ?", new String[]{productID});
                            }else if(!quantity.trim().equals("")){
                                dbConnector.insert("INSERT INTO sales_details(sales_id, product_id, quantity_sold, warranty_duration, sales_type) VALUES(?,?,?,?,?)", new String[]{rs.getString(1), productID, quantity, warranty, purchaseType});
                                dbConnector.update("UPDATE product SET physical_count = physical_count - ? WHERE product_id = ?", new String[]{quantity, productID});
                            }
                            }
                        }
                        rs.close();
                        //clear inputs and close dialogs
                        salesTypeDialog.dispose();
                        cartTableManager.clearTableContents();
                        remarksInput.setText("");
                        receiptno.setText("");
                        ProductsUI.updateAdminProductsTable();
                        searchProduct();
                        JOptionPane.showMessageDialog(null, "Purchase successful!", "Success", JOptionPane.INFORMATION_MESSAGE);
                        
                    }
                }
                
            }
        }catch(SQLException sqlE){
            sqlE.printStackTrace();
            if(sqlE.getSQLState().startsWith("23")){
                JOptionPane.showMessageDialog(null, "The receipt number entered is already existing", "Existing Receipt Number", JOptionPane.ERROR_MESSAGE);
            }
            
        }catch(ParseException pe){
            pe.printStackTrace();
        }catch(ArrayIndexOutOfBoundsException ioob){
            JOptionPane.showMessageDialog(null, "Please indicate the date of sale", "Invalid Date", JOptionPane.ERROR_MESSAGE);
        }
    }
    
    public void openSalesTypeDialog(){
        try{
            boolean greaterThanQuantity = false;
            boolean lessThanOrEqualToZero = false;
            boolean noSerialNumber = false;
            int quantity = 0;
            int currentQuantity = 0;
            int warranty = 0;
            String serialNumber = "";
            for(int i = 0; i< cartTableManager.getRowCount(); i++){
                
                if(Integer.parseInt(cartTableManager.getValueAt(i, 1)) == 0){
                    quantity = Integer.parseInt(cartTableManager.getValueAt(i, 6));
                    currentQuantity = Integer.parseInt(cartTableManager.getValueAt(i, 4));
                }else if(Integer.parseInt(cartTableManager.getValueAt(i, 1)) > 0){
                    warranty = Integer.parseInt(cartTableManager.getValueAt(i, 1));
                    serialNumber = cartTableManager.getValueAt(i,5);
                }
                String productName = cartTableManager.getValueAt(i, 2);

                if(warranty == 0 && quantity>currentQuantity && quantity > 0){
                    greaterThanQuantity = true;

                    JOptionPane.showMessageDialog(null, "The set quantity sold for " + productName + " exceeds the count in stock. \n Please check the quantity before proceeding.", "Input Error", JOptionPane.ERROR_MESSAGE);
                    break;
                }
                if(warranty == 0 && quantity <= 0){
                    lessThanOrEqualToZero = true;
                    JOptionPane.showMessageDialog(null, "The set quantity sold for " + productName + " is invalid. \n Please check the quantity before proceeding.", "Input Error", JOptionPane.ERROR_MESSAGE);
                     break;
                }
                if(warranty > 0 && serialNumber.equals("")){
                    noSerialNumber = true;
                JOptionPane op = new JOptionPane("Please input the serial number for " + productName + ".",JOptionPane.ERROR_MESSAGE);
                    JOptionPane.showMessageDialog(null, "Please input the serial number for " + productName + ".", "Input Error", JOptionPane.ERROR_MESSAGE);
                     break;
                }
                
            }
            if(cartTableManager.getRowCount() == 0){
                JOptionPane op = new JOptionPane("There are no items to checkout.",JOptionPane.ERROR_MESSAGE);
                JDialog dialog = op.createDialog("Checkout Error");
                dialog.setAlwaysOnTop(true); //<-- this line
                dialog.setModal(true);
                dialog.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
                dialog.setVisible(true); 
               // JOptionPane.showMessageDialog(null, "There are no items placed in the cart. Cannot checkout", "Input Error", JOptionPane.ERROR_MESSAGE);
            }
            if(!greaterThanQuantity && !lessThanOrEqualToZero && !noSerialNumber && cartTableManager.getRowCount() != 0){
                salesTypeDialog.setVisible(true);
            }
       }catch(NumberFormatException | NullPointerException nfe){
           nfe.printStackTrace();
           JOptionPane.showMessageDialog(null, "Please set the quantity of all items before proceeding.", "Input Error", JOptionPane.ERROR_MESSAGE);
       }catch(Exception e){
           e.printStackTrace(); 
      }
    }
    
    public void clearList(){
        int result = JOptionPane.showConfirmDialog(null, "Are you sure you want to clear the list?", "Confirm Checkout", JOptionPane.YES_NO_OPTION);
        if(result == 0){
        cartTableManager.clearTableContents();
        }
    }
    
    public void searchProduct(){
        try{
            String productName = inventorySearchInput.getText();
        ArrayList<Product> productList = productController.getProducts();
        inventoryTableManager.clearTableContents();
        
        ArrayList<Product> filteredByCategoryList = filterByCategory(productList);
        ArrayList<Product> filteredBySupplierAndCategoryList = filterBySupplier(filteredByCategoryList);
        for(Product product: filteredBySupplierAndCategoryList){
            if(product.getName().toLowerCase().contains(productName.toLowerCase())){
                if(Integer.parseInt(product.getPhysicalCount()) > 0){
                String[] adminCompleteValues = {product.getProductID(), product.getWarranty(), product.getName(), 
                     product.getSupplierName(),
                     product.getPhysicalCount(), 
                    product.getReorderQuantityLevel(), product.getUnit()};
                inventoryTableManager.addRowContent(adminCompleteValues);
                }
            }
        }
        if(productName.equals("")){
            clearMark.setVisible(false);
        }else{
            clearMark.setVisible(true);
        }
        }catch(Exception e){
            e.printStackTrace();
        }
    }
    
    public void clearSearch(){
        inventorySearchInput.setText("");
        searchProduct();
        clearMark.setVisible(false);
    }
    
    public void closeSalesTypeDialog(){
        salesTypeDialog.dispose();
    }
    
    public void removeSelectedRow(){
        cartTableManager.deleteRow();
    }
    
    public void justDClickIt(JTable table){
        table.addMouseListener(new MouseAdapter() {
        public void mousePressed(MouseEvent me) {
            JTable table =(JTable) me.getSource();
            Point p = me.getPoint();
            int row = table.rowAtPoint(p);
            if (me.getClickCount() == 2) {
                addToCart();
            }
        }
    });
    }
    
        public void justDClickIt2(JTable table){
    table.addMouseListener(new MouseAdapter() {
    public void mousePressed(MouseEvent me) {
        JTable table =(JTable) me.getSource();
        Point p = me.getPoint();
        int row = table.rowAtPoint(p);
        if (me.getClickCount() == 2) {
            editDialog();
        }
    }
});
    }
    
     public void justDClickItToDelete(JTable table){
    table.addMouseListener(new MouseAdapter() {
    public void mousePressed(MouseEvent me) {
        JTable table =(JTable) me.getSource();
        Point p = me.getPoint();
        int row = table.rowAtPoint(p);
        if (me.getClickCount() == 2) {
            removeSelectedRow();
        }
    }
});
    }
     
     public void filterProducts(){
         try{

         ArrayList<Product> productList = productController.getProducts();          
         ArrayList<Integer> coloredRows = new ArrayList<Integer>();
         if(productFilterCategoryComboBox.getSelectedItem()!=null && productList != null && productFilterSupplierComboBox.getSelectedItem()!=null){
            inventoryTableManager.clearTableContents();
            ArrayList<Product> filteredByCategoryList = filterByCategory( productList);
            ArrayList<Product> filteredByCategoryAndSupplierList = filterBySupplier(filteredByCategoryList);
            
            if(clearMark.isVisible()){
                searchProduct();
            }else{
                int rowCount = 0;
                for(Product product:filteredByCategoryAndSupplierList){
                        String[] productValues = {product.getProductID(), product.getWarranty(), product.getName(), 
                            product.getSupplierName(),
                            product.getPhysicalCount(), 
                            product.getReorderQuantityLevel(), product.getUnit()};
                        rowCount++;
                        inventoryTableManager.addRowContent(productValues);
                        if(Integer.parseInt(product.getPhysicalCount()) <= Integer.parseInt(product.getReorderQuantityLevel())){
                            //coloredRows.add(inventoryTableManager.getRowCount()-1);
                            coloredRows.add(rowCount);
                        }
                }
                //inventoryTableManager.setRowStatusColor(coloredRows, Color.PINK);
                
            }
         }   
         }catch(Exception e){
             e.printStackTrace();
         }
    }
     
     public ArrayList<Product> filterByCategory(ArrayList<Product> productList){
         ArrayList<Product> filteredProductList = new ArrayList<Product>();
         if(productFilterCategoryComboBox.getSelectedItem().toString().equals("All")){
             return productList;
         }else{
            for(Product product:productList){
                if(productFilterCategoryComboBox.getSelectedItem().toString().equals(product.getTypeName())){
                    filteredProductList.add(product);
                }
            }
            return filteredProductList;
         }
     }
     public ArrayList<Product> filterBySupplier(ArrayList<Product> productList){
         ArrayList<Product> filteredProductList = new ArrayList<Product>();
         if(productFilterSupplierComboBox.getSelectedItem().toString().equals("All")){
             return productList;
         }else{
            for(Product product:productList){
                if(productFilterSupplierComboBox.getSelectedItem().toString().equals(product.getSupplierName())){
                    filteredProductList.add(product);
                    
                }
            }
            return filteredProductList;
         }
     }
     
    public void inputSerialDialog(){
         String productID = (String) inventoryTableManager.getValueAt(inventoryTableManager.getSelectedRow(), 0);
         String name = (String) inventoryTableManager.getValueAt(inventoryTableManager.getSelectedRow(), 2);
         String supplier = (String) inventoryTableManager.getValueAt(inventoryTableManager.getSelectedRow(), 3);
         String quantity = (String)  inventoryTableManager.getValueAt(inventoryTableManager.getSelectedRow(), 4);
         String warranty = (String) inventoryTableManager.getValueAt(inventoryTableManager.getSelectedRow(), 1);
         String value = inputSerial.getText();

                    
                    
                 if(value.isEmpty()){
                  JOptionPane.showMessageDialog(null, "Please enter the serial number.", "Input Error", JOptionPane.ERROR_MESSAGE);   
                 }else{
                 cartTableManager.addRowContent(new String[]{productID, warranty, name, supplier, quantity, "Purchase", value, "1"});
                 cartTableManager.addComboBoxToCell(5, new String[]{"Purchase","Service"});
                 inputSerialDialog.dispose();
                 }
        }
     
     public void inputQuantityDialog(){
         try{
         String productID = (String) inventoryTableManager.getValueAt(inventoryTableManager.getSelectedRow(), 0);
         String name = (String) inventoryTableManager.getValueAt(inventoryTableManager.getSelectedRow(), 2);
         String supplier = (String) inventoryTableManager.getValueAt(inventoryTableManager.getSelectedRow(), 3);
         String quantity = (String)  inventoryTableManager.getValueAt(inventoryTableManager.getSelectedRow(), 4);
         String warranty = (String) inventoryTableManager.getValueAt(inventoryTableManager.getSelectedRow(), 1);
         String value = inputQuantity.getText();
         
         int currentQuantity = Integer.parseInt(quantity);
         int inputValue = Integer.parseInt(value);
         
         
         if(currentQuantity >= inputValue){
             if(value.isEmpty()){   
                 JOptionPane.showMessageDialog(null, "Please enter a quantity.", "Input Error", JOptionPane.ERROR_MESSAGE);
             }else{
                 if(inputValue > 0){
                 cartTableManager.addRowContent(new String[]{productID, warranty, name, supplier, quantity, "Purchase", "", value});
                 cartTableManager.addComboBoxToCell(5, new String[]{"Purchase","Service"});
                 inputQuantityDialog.dispose();
                 }else{
                  JOptionPane.showMessageDialog(null, "Please enter a valid quantity.", "Input Error", JOptionPane.ERROR_MESSAGE);  
                 }
             }
         }else{
             JOptionPane.showMessageDialog(null, "Insufficient Stock.", "Input Error", JOptionPane.ERROR_MESSAGE);
         }
         }catch(NumberFormatException nfe){
             JOptionPane.showMessageDialog(null, "Please enter a valid quantity.", "Input Error", JOptionPane.ERROR_MESSAGE);
         }
             }
     
     public void editDialog(){
         String quantity = cartTableManager.getValueAt(cartTableManager.getSelectedRow(), 7);
         String serial = cartTableManager.getValueAt(cartTableManager.getSelectedRow(), 6);
         if(serial.equals("")){
             editQuantityDialog.setVisible(true);
         }else{
             editSerialDialog.setVisible(true);
         }
     }
     
     public void editQuantityDialog(){
         try{
         String quantity = editQuantity.getText();
         String physCount = cartTableManager.getValueAt(cartTableManager.getSelectedRow(), 4);
         int quant = Integer.parseInt(quantity);
         int count = Integer.parseInt(physCount);
         if(count < quant){
             editQuantity.setText("");
             JOptionPane.showMessageDialog(null, "Insufficient Stock", "Input Error", JOptionPane.ERROR_MESSAGE);
         }else if(quantity.isEmpty()){
             JOptionPane.showMessageDialog(null, "Please enter a quantity.", "Input Error", JOptionPane.ERROR_MESSAGE);
         }else if(quant < 1){
             JOptionPane.showMessageDialog(null, "Please enter a valid quantity.", "Input Error", JOptionPane.ERROR_MESSAGE);
         }else{
            cartTableManager.setValueAt(cartTableManager.getSelectedRow(), 7, quantity);
            editQuantity.setText("");
            editQuantityDialog.dispose();
         }
         }catch(NumberFormatException nfe){
             JOptionPane.showMessageDialog(null, "Please Enter a valid quantity.", "Input Error", JOptionPane.ERROR_MESSAGE);
         }
     }
     
     public void editSerialDialog(){
         String serial = editSerial.getText();
         cartTableManager.setValueAt(cartTableManager.getSelectedRow(), 6, serial);
         editSerial.setText("");
         editSerialDialog.dispose();
     }
     
     public void updateSalesHistory(){
        salesHistoryTableManager.clearTableContents();
        DateFormat dfto = new SimpleDateFormat("yyyy-MM-dd");
        SimpleDateFormat sdf = new SimpleDateFormat("MMMMM d, yyyy");
        String toDate = InputValidator.dateFormat(dateFrom);
        String fromDate = InputValidator.dateFormat(dateTo);
        try{
            ResultSet rs = dbConnector.query("SELECT sales_date, Name, quantity_sold, receipt_number, serial_number, sales_type, remarks FROM sales JOIN sales_details using(sales_id) JOIN product using(Product_id) WHERE sales.sales_id = sales_details.sales_id AND sales_details.product_id = product.Product_id AND sales_date between '" + toDate + "' and '" + fromDate + "' ORDER BY 1 DESC");

            while(rs.next()){
                
                String date = rs.getString("sales_date");
                Date dateFormat = dfto.parse(date);
                String dateReport = sdf.format(dateFormat);
                String name = rs.getString("Name");
                String quantity = rs.getString("quantity_sold");
                if(quantity.equals("0")){
                    quantity = "Partial";
                }
                String description = rs.getString("receipt_number");
                String serial = rs.getString("serial_number");
                String type = rs.getString("sales_type");
                String remarks = rs.getString("remarks");
                String[] reportDetails = {dateReport, name, quantity, description, remarks, serial, type};
                salesHistoryTableManager.addRowContent(reportDetails);
            }
        }catch(SQLException sqlE){
            sqlE.printStackTrace();
        }catch(Exception e){
            e.printStackTrace();
        }
    }
}
